package cn.itsource.smartcampus.interceptor;

import cn.itsource.smartcampus.util.TokenMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
/**
 * HandlerInterceptor这个接口是框架自带的拦截器
 *
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp,Object handler) throws IOException {

        System.out.println("进入到拦截器中");
        //从本地储存对象中进入到token中
       String token = req.getHeader("access-token");
       String parameter_token = req.getParameter("access-token");

       String type = req.getParameter("type");
        System.out.println(parameter_token+",,,,,,,"+type);
        //System.out.println("进入到拦截器了");
        /**
         * 字符串的工具类，判断得到的令牌是否为空
         */
        if(StringUtils.isNotBlank(parameter_token)
                        && StringUtils.isNotBlank(type)
                        && TokenMap.getTokenMap(parameter_token )!= null){
            return true;
        }
        Object o = TokenMap.getTokenMap(token);
        if(" ".equals(o)||null==o){
            //告诉前端我响应的是一个json
            resp.setContentType("application/json;charset=UTF-8");
            //设置响应数据
            PrintWriter writer = resp.getWriter();
            writer.write("{\"code\":\"401\"}");
            return false;
        }
        //登录成功了，放行
        return true;

    }

}
